/**
 * 
 */
package co.fitstart.admin.web.controller.user.coupon;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.BusinessException;
import com.demo2do.core.support.Page;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.utils.WebUtils;

import co.fitstart.admin.entity.content.CouponSearch;
import co.fitstart.admin.entity.security.Login;
import co.fitstart.admin.service.CouponService;
import co.fitstart.admin.service.DataService;
import co.fitstart.admin.web.controller.user.satisfaction.GiftCouponController;
import co.fitstart.admin.web.interceptor.MenuSetting;
import co.fitstart.admin.web.resolver.Secure;
import co.fitstart.admin.web.view.ExcelTemplateView;
import co.fitstart.entity.coupon.Coupon;
import co.fitstart.entity.coupon.CouponBatch;
import co.fitstart.entity.user.User;

/**
 * @author mohanlan
 *
 */
@Controller
@RequestMapping("outside-coupons")
@MenuSetting("menu-user")
public class OutsideCouponController {
	
	private static final Logger logger = LoggerFactory.getLogger(GiftCouponController.class);

    @Autowired
    private CouponService<CouponBatch> couponBatchService;
    
    @Autowired
    @Qualifier("dataService")
    private DataService<Coupon> couponService;
    
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @MenuSetting("submenu-coupon-management")
    public ModelAndView list(HttpServletRequest request, Page page) {
        
    	ModelAndView modelAndView = new ModelAndView("user/coupon-management/coupon-list");
        
    	CouponBatch couponBatch = couponBatchService.getCouponBatch(new Long(21));
        List<Coupon> coupons = couponBatchService.listCoupons(couponBatch, page);
        
        modelAndView.addObject("couponBatch", couponBatch);
        modelAndView.addObject("coupons", coupons);
        modelAndView.addObject("page", page);
    	
        return modelAndView;
    }

    /**
     * 
     * @param code
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    @MenuSetting("submenu-coupon-management")
    public ModelAndView search() {
        ModelAndView modelAndView = new ModelAndView("user/coupon-management/coupon-search");
        
        return modelAndView;
    }
    
    /**
     * Do search
     * 
     * @param couponSearch
     * @param request
     * @param page
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params = "filter")
    @MenuSetting("submenu-coupon-management")
    public ModelAndView onSearch(CouponSearch couponSearch, HttpServletRequest request, Page page) {
        
    	ModelAndView modelAndView = new ModelAndView("user/coupon-management/coupon-list");
    	CouponBatch couponBatch = couponBatchService.getCouponBatch(new Long(21));
    	couponSearch.setBatch(couponBatch);
    	
        List<Coupon> coupons = couponBatchService.searchCoupon(couponSearch, page);
        
        modelAndView.addObject("coupons", coupons);
        modelAndView.addObject("refer", "search");
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));
        
        return modelAndView;
        
    }
    
    /**
     * 
     * @param couponId
     * @return
     */
    @RequestMapping(value = "/use", method = RequestMethod.GET)
    @MenuSetting("submenu-coupon-management")
    public ModelAndView usebysearch() {
        ModelAndView modelAndView = new ModelAndView("user/coupon-management/coupon-search-use");
        
        
        
        return modelAndView;
    }
    
    /**
     * 
     * @param couponId
     * @return
     */
    @RequestMapping( value = "/use", method = RequestMethod.PATCH)
    public @ResponseBody String onSearchUse(@RequestParam("couponCode") String couponCode) {
        
        Result result = new Result();
        
        try {
        	
            Coupon coupon = couponBatchService.loadCoupon(couponCode);
            couponBatchService.useCoupon(coupon);
            
            result.success().message("优惠券核销成功！");
        } catch(BusinessException e) {
            result.fail().message(e.getMessage());
        } catch(Exception e) {
            logger.error("use error", e);
            
            result.fail().message("优惠券核销失败！");
            
        }
        
        return JsonUtils.toJsonString(result);
    }

    /**
     * 
     * @param couponId
     * @return
     */
    @RequestMapping(value = "/{couponId}/use", method = RequestMethod.GET)
    @MenuSetting("submenu-coupon-management")
    public ModelAndView use(@PathVariable("couponId") Long couponId) {
        ModelAndView modelAndView = new ModelAndView("user/coupon-management/coupon-use");
        
        modelAndView.addObject("couponId", couponId);
        
        return modelAndView;
    }

    /**
     * 
     * @param couponId
     * @return
     */
    @RequestMapping( value = "/{couponId}/use", method = RequestMethod.PATCH)
    public @ResponseBody String onUse(@PathVariable("couponId") Long couponId) {
        
        Result result = new Result();
        
        try {
        	
            Coupon coupon = couponService.load(Coupon.class, couponId);
            couponBatchService.useCoupon(coupon);
            
            result.success().message("优惠券核销成功！");
            
        } catch(BusinessException e) {
            result.fail().message(e.getMessage());
        } catch(Exception e) {
            logger.error("use error", e);
            
            result.fail().message("优惠券核销失败！");
            
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "/create-view", method = RequestMethod.GET)
    @MenuSetting("submenu-coupon-management")
    public ModelAndView createCoupon() {
        ModelAndView modelAndView = new ModelAndView("user/coupon-management/coupon-create");
        
        modelAndView.addObject("today", DateFormatUtils.format(new Date(), "yyyy-MM-dd"));
        
        return modelAndView;
    }
    
    @RequestMapping(value = "/create", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@MenuSetting("submenu-store-sku-management")
	public @ResponseBody String onCreateCoupon(@RequestParam("mobile") String mobile) {
    	
    	Result result = new Result();

		try {
			
			User user = new User();
			user.setMobile(mobile);
			couponBatchService.generateCoupon(new Long(21), user);
			
			result.success();

		} catch (BusinessException be) {

			logger.error("omInportCoupon - create fail, exception [{}]", be.getMessage());
			result.fail("501").message(be.getMessage());

		} catch (Exception e) {
			result.fail("500").message(e.getMessage());
			logger.error("omInportCoupon - create fail, exception [{}]", e);
		}

		return JsonUtils.toJsonString(result);

	}
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "/import-view", method = RequestMethod.GET)
    @MenuSetting("submenu-coupon-management")
    public ModelAndView importCoupon() {
        ModelAndView modelAndView = new ModelAndView("user/coupon-management/coupon-import");
        
        modelAndView.addObject("today", DateFormatUtils.format(new Date(), "yyyy-MM-dd"));
        
        return modelAndView;
    }
    
    /**
     * 
     * @param file
     * @return
     */
    @RequestMapping(value = "/import", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@MenuSetting("submenu-store-sku-management")
	public @ResponseBody String omInportCoupon( @RequestParam("file") MultipartFile file) {
    	
    	Result result = new Result();

		try {
			
			couponBatchService.generateCoupon(new Long(21), file.getInputStream());

			result.success();

		} catch (BusinessException be) {

			logger.error("omInportCoupon - create fail, exception [{}]", be.getMessage());
			result.fail("501").message(be.getMessage());

		} catch (Exception e) {

			logger.error("omInportCoupon - create fail, exception [{}]", e);
		}

		return JsonUtils.toJsonString(result);

	}
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "/export-view", method = RequestMethod.GET)
    @MenuSetting("submenu-coupon-management")
    public ModelAndView exportView() {
        ModelAndView modelAndView = new ModelAndView("user/coupon-management/coupon-export");
        
        modelAndView.addObject("today", DateFormatUtils.format(new Date(), "yyyy-MM-dd"));
        
        return modelAndView;
    }

    /**
     * 
     * @param login
     * @param siteId
     * @param beginDate
     * @param endDate
     * @return
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public ModelAndView onExport(@Secure Login login,
                                 @RequestParam(value = "beginDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date beginDate,
                                 @RequestParam(value = "endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {
    	
        ModelAndView modelAndView = new ModelAndView(new ExcelTemplateView("outside-coupon-report.xls"));
        
        modelAndView.addObject("beginDate", DateFormatUtils.format(beginDate, "yyyy-MM-dd"));
        modelAndView.addObject("endDate", DateFormatUtils.format(endDate, "yyyy-MM-dd"));
        
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        modelAndView.addObject("fmt", fmt);
        
        return modelAndView;
    }
	
}
